function Toast(msg, duration) {
	duration = isNaN(duration) ? 3000 : duration;
	var m = document.createElement('div');
	m.innerHTML = msg;
	m.style.cssText =
		"max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background: rgba(255,106,106,.5);font-size: 16px;";
	document.body.appendChild(m);
	setTimeout(function() {
		var d = 0.5;
		m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
		m.style.opacity = '0';
		setTimeout(function() {
			document.body.removeChild(m)
		}, d * 1000);
	}, duration);
}
var socket;
if (typeof(WebSocket) == "undefined") {
	Toast("不支持的浏览器", 2000);
} else {
	socket = new WebSocket("wss://www.meetion.ren/x-chat/server/admin");
	socket.onopen = function() {
		console.log("连接成功");
		var timer = setInterval(function() {
			try {
				socket.send('HEARTCHECK');
			} catch (e) {
				clearInterval(timer);
			}			
		}, 10000);
	};
	socket.onmessage = function(msg) {
		Toast(msg.data, 2000);
	};
	socket.onclose = function() {
		socket = new WebSocket("wss://www.meetion.ren/x-chat/server/admin");
	};
	socket.onerror = function() {
		alert("Socket发生了错误");
	}
}
var chat_iput = document.getElementById('chat_iput');
var input = document.getElementById('input');
chat_iput.style.bottom = (-20) + 'px';
var that = this;

function getX(e) {
	e = e || window.event;
	return e.pageX || e.clientX + document.body.scroolLeft;
}

function getY(e) {
	e = e || window.event;
	return e.pageY || e.clientY + document.body.scrollTop;
}
document.onclick = function(e) {
	var top = chat_iput.offsetTop;
	var left = chat_iput.offsetLeft;
	var height = chat_iput.scrollHeight;
	var width = chat_iput.scrollWidth;
	var mouseX = getX(e);
	var mouseY = getY(e);
	if (mouseX > left && mouseX < left + width && mouseY > top && mouseY < top + height) {
		return;
	} else {
		close();
	}
};

function show() {
	if (chat_iput.offsetTop >= 10) {
		return;
	}
	var timer = setInterval(function() {
		if (chat_iput.offsetTop >= 10) {
			clearTimeout(timer);
		}
		chat_iput.style.top = chat_iput.offsetTop + 1 + 'px';
	}, 1);
	input.disabled = false;
	input.focus();
}

function close() {
	var height = chat_iput.offsetHeight;
	if (chat_iput.offsetTop <= -(height - 20)) {
		return;
	}
	var timer = setInterval(function() {
		if (chat_iput.offsetTop <= -(height - 20)) {
			clearTimeout(timer);
		}
		chat_iput.style.top = chat_iput.offsetTop - 1 + 'px';
	}, 10);
	input.disabled = true;
}

function submit(e) {
	var evt = window.event || e;
	if (evt.keyCode == 13) {
		socket.send(input.value);
		input.value = "";
	}
}
